<template>
  <div class="talk">
    <button @click="getLoveTalk">获取一句土味情话</button>
    <ul>
      <li v-for="talk in talkStore.talkList" :key="talk.id">
        {{ talk.content }}
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts" name="LoveTalk">
import axios from "axios";
import {nanoid} from "nanoid";
import useTalkStore from "@/store/talk.ts";

/**
 * 这里的 useTalkStore() 调用了 store/talk.ts 文件中的 useTalkStore() 函数，
 */
const talkStore = useTalkStore();

/**
 * 订阅 store 中的数据变化
 */
talkStore.$subscribe((mutation, state) => {
  console.log('保存的数据发生变化', mutation, state);
  sessionStorage.setItem('talkList', JSON.stringify(state.talkList));
});

/**
 * 获取土味情话
 */
const getLoveTalk = async () => {
  // 发请求，下面这行的写法是：联系结构赋值 + 重命名
  let {data: {content: title}} = await axios.get('https://api.uomg.com/api/rand.qinghua?format=json');
  // 把请求回来的字符串，包装一个对象
  let obj = {id: nanoid(), content: title}
  talkStore.talkList.unshift(obj)
}
</script>

<style scoped lang="scss">
.talk {
  background-color: pink;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 0 0 10px;
}
</style>
